#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：NoBad 
@File    ：view.py
@Author  ：LYP
@Date    ：2025/10/30 13:26 
@description :
"""
from rest_framework import serializers



from models.models import WeChatPayOrder,WeChatUser,Product
from tool.token_tools import _redis
from tool.base_views import BaseViewSet
from tool.utils import CustomPagination, ApiResponse
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiParameter

class WxPayOrderSerializer(serializers.ModelSerializer):
    product_type_name = serializers.CharField(source="product.product_type")
    product_name = serializers.CharField(source="product.name")

    class Meta:
        model = WeChatPayOrder
        fields = '__all__'


@extend_schema(tags=["微信支付订单"])
@extend_schema_view(
    list=extend_schema(summary="获取微信支付表",
        parameters=[
            OpenApiParameter(name="trade_state", type=str, required=False, description="支付状态(SUCCESS, 支付成功), (REFUND, 转入退款), (NOTPAY, 未支付)"),
            ], responses={200: WxPayOrderSerializer(many=True), }),
    retrieve=extend_schema(summary="获取微信支付详情",
                           responses={200: WxPayOrderSerializer, 404: "用户不存在"}),
    update=extend_schema(
        summary="更新微信支付订单", request=WxPayOrderSerializer),
    partial_update=extend_schema(summary="部分微信支付订单", request=WxPayOrderSerializer),
    destroy=extend_schema(summary="删除微信支付订单", description="删除指定用户，仅管理员可操作",
                          responses={204: "删除成功", 404: "用户不存在"}
                          )
)
class WxPayOrderViewSet(BaseViewSet):
    queryset = WeChatPayOrder.objects.all()
    serializer_class = WxPayOrderSerializer
    pagination_class = CustomPagination

    def get_queryset(self):
        """
               获取订单查询集，支持按用户筛选
       """
        queryset = super().get_queryset()
        # 获取查询参数
        trade_state = self.request.query_params.get('trade_state')
        # 应用过滤条件
        if trade_state:
            queryset = queryset.filter(trade_state=trade_state)
        # 从请求头获取 token
        token = self.request.headers.get("token")
        if not token:
            return queryset
        # 从 Redis 获取 openId
        openId = _redis.getKey(token)
        print(openId)
        if not openId:
            return queryset
        # 如果 openId 长度大于 10，则查询用户并筛选订单
        if len(openId) > 10:
            try:
                user = WeChatUser.objects.get(open_id=openId)
                queryset = queryset.filter(payer_id=user.id)
            except WeChatUser.DoesNotExist:
                pass  # 用户不存在，返回空结果
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            # 使用自定义分页响应
            return self.get_paginated_response(serializer.data)
        # 如果没有分页，返回普通响应
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)
